package com.heima.common.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;

/**
 * @author itheima
 * @since 2022-07-13
 */
@Component
@Slf4j
public class FreemarkerGenerator {

    @Autowired
    private Configuration configuration;

    /**
     * 生成静态文件
     *
     * @param templateName 模板文件
     * @param params       模板数据
     * @return 输入流
     */
    public InputStream generate(String templateName, Map params) {
        if (StringUtils.isEmpty(templateName)) {
            log.warn("模板名不能为空");
            return null;
        }

        try {
            Template template = configuration.getTemplate(templateName);
            StringWriter out = new StringWriter();
            template.process(params, out);
            return new ByteArrayInputStream(out.toString().getBytes());
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }

        return null;
    }
}
